package com.chookss.video;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.KnowledgeEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.MaxHeightRecyclerView;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//只用于发布或者修改视频选择目录   还有图库发布
public class VideoNewCatesSecondActivity2 extends BaseAct {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.topFlowLayout)
    RecyclerView titleRcv;
    @BindView(R.id.rcvDirectory)
    RecyclerView recyclerView;
    @BindView(R.id.tvBottom)
    TextView tvBottom;
    @BindView(R.id.tvBottomSure)
    TextView tvBottomSure;
    @BindView(R.id.llLine2)
    View llLine2;
    @BindView(R.id.llBottomSure)
    LinearLayout llBottomSure;
    @BindView(R.id.ivBottomArrow)
    ImageView ivBottomArrow;
    @BindView(R.id.llBottomArrow)
    LinearLayout llBottomArrow;
    @BindView(R.id.llBottomPopup)
    LinearLayout llBottomPopup;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.smrRf)
    SmartRefreshLayout smrRf;
    @BindView(R.id.folderFlowLayout)
    MaxHeightRecyclerView folderSelectLayout;
    @BindView(R.id.consecutiveScrollerLayout)
    ConsecutiveScrollerLayout consecutiveScrollerLayout;
    private boolean isOpen = false;//是否展开弹窗默认关闭
    private String videoType = "2";//1小视频2长视频 3发布或者修改视频所用4图库7图文
    private List<KnowledgeEntity> folderList = new ArrayList<>();
    private FolderAdapter adapter;
    private int level = 1;//默认层级
    //目录
    private TitleAdapter titleAdapter;
    private ArrayList<String> nameList = new ArrayList<>();//组织排列;
    private String parentCode = "", parentName = "", parentFileNum = "";//各个层级需要传的
    private KnowledgeEntity oldDepartmentEntity = null;//上一层级归属部门实体类
    private KnowledgeEntity levelOne;//一级目录数据

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_video_cates_second);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        videoType = getIntent().getStringExtra("videoType");
        parentCode = getIntent().getStringExtra("parentCode");
        parentName = getIntent().getStringExtra("parentName");
        parentFileNum = getIntent().getStringExtra("parentFileNum");
        level = getIntent().getIntExtra("level", 1);
        levelOne = (KnowledgeEntity) getIntent().getSerializableExtra("levelOne");
        ArrayList<String> nameLists = getIntent().getStringArrayListExtra("nameList");
        if (nameLists != null) {
            nameList.addAll(nameLists);
        }
        if (nameList.size() > 1) {
            tvTitle.setText(nameList.get(nameList.size() - 1));
            titleAdapter = new TitleAdapter(R.layout.item_folder_name_list, this, nameList);
            LinearLayoutManager lm = new LinearLayoutManager(this);
            lm.setOrientation(LinearLayoutManager.HORIZONTAL);
            titleRcv.setLayoutManager(lm);
            titleRcv.setAdapter(titleAdapter);
            titleRcv.setVisibility(View.VISIBLE);
            llLine2.setVisibility(View.VISIBLE);
        } else {
            if (oldDepartmentEntity != null) {
                tvTitle.setText(oldDepartmentEntity.getName());
            } else if (!Utils.isNull(parentName)) {
                tvTitle.setText(parentName);
            }

        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new FolderAdapter(R.layout.item_video_folder, this, folderList, nameList, level, videoType);
        recyclerView.setAdapter(adapter);
        folderSelectLayout.setVisibility(View.GONE);
        smrRf.setEnableLoadMore(false);
        smrRf.setEnableRefresh(false);
        getCatalogData();
    }

    private void getCatalogData() {
        Map<String, String> map = new HashMap<>();
        map.put("parentCode", parentCode);
        //        fileFlag 0不包含当前目录文件 1包含
        String url = "";
        if ("3".equals(videoType)) {
            url = Urls.selectAPPCatalogTreeGlobal;
            map.put("fileFlag", "0");
            map.put("totalFlag", "0");
            map.put("catalogType", "1");
        } else if ("4".equals(videoType)) {
            url = Urls.getAppImageCatalogTree;
            map.put("fileFlag", "0");
            map.put("totalFlag", "0");
        } else if ("7".equals(videoType)) {
            url = Urls.getAppImageTextCatalogTree;
            map.put("fileFlag", "0");
            map.put("totalFlag", "0");
        } else {
            url = Urls.selectAPPCatalogTreeGlobal;
            map.put("fileFlag", "1");
            map.put("totalFlag", "1");
            map.put("catalogType", videoType);
        }
        showLoading();
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<KnowledgeEntity>>>() {
        }.getType(), null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<KnowledgeEntity>>() {
            @Override
            public void onSuccess(List<KnowledgeEntity> data) {
                dismissLoading();
                if (data != null && data.size() > 0) {
                    folderList.clear();
                    folderList.addAll(data);
                    for (int i = 0; i < folderList.size(); i++) {
                        for (int j = 0; j < MyApp.videoFolderList.size(); j++) {
                            if (folderList.get(i).getCode().equals(MyApp.videoFolderList.get(j).getCode())) {
                                folderList.get(i).setSelect(true);
                            }
                        }
                    }
                    adapter.notifyDataSetChanged();
                    llNone.setVisibility(View.GONE);
                    smrRf.setVisibility(View.VISIBLE);
                } else {
                    llNone.setVisibility(View.VISIBLE);
                    smrRf.setVisibility(View.GONE);
                }
                if (level > 1) {
                    if (MyApp.videoFolderList.size() == 0) {
                        KnowledgeEntity knowledgeEntity = new KnowledgeEntity();
                        knowledgeEntity.setCode(parentCode);
                        knowledgeEntity.setName(parentName);
                        knowledgeEntity.setFileNum(parentFileNum);
                        MyApp.videoFolderList.add(knowledgeEntity);
                    }
                }
                changeSelectStatus();
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class FolderAdapter extends BaseQuickAdapter<KnowledgeEntity, BaseViewHolderEx> {
        private Activity context;
        private int level;//层级
        private boolean isTask = false;
        private ArrayList<String> nameList;//组织排列
        private String catalogType;//自定义专属字段

        public FolderAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<KnowledgeEntity> data, ArrayList<String> nameList, int level, String catalogType) {
            super(layoutResId, data);
            this.context = context;
            this.nameList = nameList;
            this.level = level;
            this.catalogType = catalogType;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, KnowledgeEntity entity) {
            TextView tvItemTitle = helper.getView(R.id.tvItemTitle);
            TextView tvInit = helper.getView(R.id.tvInit);
            TextView tvInit2 = helper.getView(R.id.tvInit2);
            LinearLayout llAll = helper.getView(R.id.llAll);
            ImageView ivType = helper.getView(R.id.ivType);
            ImageView ivFilesType = helper.getView(R.id.ivFilesType);
            LinearLayout llArrow = helper.getView(R.id.llArrow);
            View line = helper.getView(R.id.line);
            tvItemTitle.setText(entity.getName());
            if (entity.isSelect()) {
                llAll.setBackgroundColor(Color.parseColor("#FFF8EF"));
                line.setVisibility(View.INVISIBLE);
            } else {
                llAll.setBackgroundColor(Color.parseColor("#FFFFFF"));
                line.setVisibility(View.VISIBLE);
            }
            if (entity.getCode().contains("X")) {
                ivType.setVisibility(View.GONE);
                ivFilesType.setVisibility(View.VISIBLE);
                llArrow.setVisibility(View.INVISIBLE);
            } else {
                ivType.setVisibility(View.VISIBLE);
                ivFilesType.setVisibility(View.GONE);
                llArrow.setVisibility(View.VISIBLE);
            }
            if (!Utils.isNull(entity.getName())) {
                if (entity.getName().equals("我的上传")) {
                    tvInit.setVisibility(View.VISIBLE);
                    tvInit.setText("我共上传了" + entity.getFileNum() + "个文件");
                    tvInit2.setVisibility(View.GONE);
                } else {
                    if (Utils.isNull(entity.getFolderNum())) {
                        tvInit.setVisibility(View.GONE);
                    } else {
                        tvInit.setVisibility(View.VISIBLE);
                        tvInit.setText(entity.getFolderNum() + "个文件夹");
                    }
                    if (Utils.isNull(entity.getFileNum())) {
                        tvInit2.setVisibility(View.GONE);
                    } else {
                        tvInit2.setVisibility(View.VISIBLE);
                        tvInit2.setText(entity.getFileNum() + "个文件");
                    }
                }
            }

            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (entity.isSelect()) {
                        if (MyApp.videoFolderList.size() > 0) {
                            HashMap<String, String> map = new HashMap<>();
                            map.put("clear_folder_code", MyApp.videoFolderList.get(0).getCode());
                            EventBus.getDefault().post(new MyEvent(map));
                        }
                        MyApp.videoFolderList.clear();
                    } else {
                        if (MyApp.videoFolderList.size() > 0) {
                            HashMap<String, String> map = new HashMap<>();
                            map.put("clear_folder_code", MyApp.videoFolderList.get(0).getCode());
                            EventBus.getDefault().post(new MyEvent(map));
                        }
                        MyApp.videoFolderList.clear();
                        folderList.get(helper.getItemPosition()).setSelect(true);
                        MyApp.videoFolderList.add(entity);
                        adapter.notifyItemChanged(helper.getItemPosition());
                    }
                    changeSelectStatus();
                }
            });
            llArrow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, VideoNewCatesSecondActivity2.class);
                    ArrayList<String> nameNewList = new ArrayList<>();//组织排列
                    nameNewList.addAll(nameList);
                    nameNewList.add(entity.getName());
                    intent.putStringArrayListExtra("nameList", nameNewList);
                    intent.putExtra("level", (level + 1));
                    intent.putExtra("parentCode", entity.getCode());
                    intent.putExtra("parentName", entity.getName());
                    intent.putExtra("parentFileNum", entity.getFileNum());
                    intent.putExtra("videoType", videoType);
                    intent.putExtra("levelOne", levelOne);
                    context.startActivity(intent);
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("VideoNewCatesSecondActivity2")) {
                int oldLevel = Utils.changeNumber(map.get("VideoNewCatesSecondActivity"));
                if (level > oldLevel) {
                    finish();
                }
            } else if (map.containsKey("clear_folder_code")) {
                String code = map.get("clear_folder_code");
                //刷新当前目录列表
                for (int i = 0; i < folderList.size(); i++) {
                    if (folderList.get(i).getCode().equals(code)) {
                        folderList.get(i).setSelect(false);
                        adapter.notifyItemChanged(i);
                    }
                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("CloseVideoNewCates".equals(msg)) {
                //刷新最近列表
                finish();
            }
        }
    }

    private void changeSelectStatus() {
        //发布视频是单选，底部弹窗么有
        llBottomPopup.setVisibility(View.GONE);
        if (MyApp.videoFolderList.size() > 0) {
            tvBottomSure.setText("上传到" + MyApp.videoFolderList.get(0).getName());
            tvBottom.setText(MyApp.videoFolderList.get(0).getFileNum() + "个文件");
        } else {
            tvBottomSure.setText("确定");
            tvBottom.setText("0个文件");
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //比onMoonEvent 慢
        changeSelectStatus();
    }

    class TitleAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Activity context;

        public TitleAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<String> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String entity) {
            TextView tvItemTitle = helper.getView(R.id.tvTitle);
            ImageView ivArrow = helper.getView(R.id.ivArrow);
            tvItemTitle.setText(entity);
            if (helper.getItemPosition() > 0) {
                ivArrow.setVisibility(View.VISIBLE);
            } else {
                ivArrow.setVisibility(View.GONE);
            }
            if (helper.getItemPosition() == nameList.size() - 1) {
                tvItemTitle.setTextColor(Color.parseColor("#333333"));
            } else {
                tvItemTitle.setTextColor(Color.parseColor("#8a8a8a"));
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }

                    HashMap<String, String> map = new HashMap<>();
                    if (helper.getItemPosition() == 0) {
                        if (levelOne != null) {
                            Intent intent = null;
                            intent = new Intent(VideoNewCatesSecondActivity2.this, VideoNewCatesSecondActivity2.class);
                            intent.putExtra("parentCode", levelOne.getCode());
                            intent.putExtra("parentName", levelOne.getName());
                            intent.putExtra("parentFileNum", levelOne.getFileNum());
                            intent.putExtra("videoType", videoType);
                            intent.putExtra("levelOne", levelOne);
                            intent.putExtra("level", 1);
                            ArrayList<String> nameList = new ArrayList<>();//组织排列
                            nameList.add(levelOne.getName());
                            intent.putStringArrayListExtra("nameList", nameList);
                            startActivity(intent);
                            MyApp.videoFolderMap.clear();
                        }
                        map.put("VideoNewCatesSecondActivity2", "0");
                        EventBus.getDefault().post(new MyEvent(map));
                    } else {
                        map.put("VideoNewCatesSecondActivity2", (helper.getItemPosition() + 1) + "");
                        EventBus.getDefault().post(new MyEvent(map));
                    }

                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        finish();

    }

    @OnClick({R.id.title_back, R.id.llBottom})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.llBottom:
                if (MyApp.videoFolderList.size() == 0) {
                    MyToast.show("最少选择一个");
                } else {
                    String codes = "", videoNames = "";
                    codes = MyApp.videoFolderList.get(0).getCode();
                    videoNames = MyApp.videoFolderList.get(0).getName();
                    Map<String, String> map = new HashMap<>();
                    map.put("videoCate", codes);
                    map.put("videoNames", videoNames);
                    EventBus.getDefault().post(new MyEvent(map));
                    EventBus.getDefault().post(new MyEvent("CloseVideoNewCates"));
                }
                break;
        }
    }


}
